<?php
namespace Services;
/**
 * File holds class for account data manipulation
 *
 * PHP version 5.3.5
 *
 * @category   CM
 * @package    Services
 * @subpackage -
 * @author     markus karileet <markuskarileet@hotmail.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @link       -
 */
class Account extends ORM {
	/**
	 * Method checks if account data in session id valid.
	 * @return \Entities\Account When check is successful, account info is 
	 * returned, false otherwise
	 */
	public function checkToken() {
		//try to read user from DB using session parameters
		$template = new \Entities\Account();
		$template->setId((int)@$_SESSION['userid']);
		$loggedUser = $this->select($template);
		$valid = false;
		//if user was found, check if session data is tampered or not
		if ($loggedUser) {
			if (@$_SESSION['token'] == sha1($loggedUser->getId() . '|' . $loggedUser->getName() . '|' . $loggedUser->getLastlogin())) {
				//session data untampered, procees
				$valid = $loggedUser;
			} else {
				//session data is corrupt, unset session and return false
				$this->clearUserData();
			}
		}
		return $valid;
	}
	
	/**
	 * Method authentices user from username and password. When match from
	 * DB is found, user info session is set and account last login time is 
	 * updated
	 * @param array $post HTML POST array 
	 * @return \Entities\Account Account info on success, false otherwise
	 */
	public function authenticate($post) {
		//Read user from DB using username and pass
		$template = new \Entities\Account();
		$template->setName($post['name']);
		$template->setPassword(sha1($post['password']));
		$authUser = $this->select($template);
		//when user is found, set sessoin data
		if ($authUser) {
			$loginTime = time();
			$_SESSION['userid'] = $authUser->getId();
			$_SESSION['token'] = sha1($authUser->getId() . '|' . $authUser->getName() . '|' . $loginTime);
			//update login time
			$authUser->setLastlogin($loginTime);
			$this->update($authUser);
		} 
		//return false or authenticated user
		return $authUser;
	}
	
	/**
	 * Method unsets user session
	 */
	public function clearUserData() {
		unset($_SESSION['token']);
		unset($_SESSION['userid']);
	}
}